<?php

include "../controller/ConectBanco.php";
header("Content-Type: application/json");

$jsonData ='';
$params = $_POST["params"];
//$params = "1@25/09/2013@@3@25/09/2013";
$jsonData .='{"ponto":[';

$arrayParams = explode("@@",$params);
foreach ($arrayParams as $indice => $valor) {
	$arrayDateTime = explode("@",  $valor);
	$idDevice = $arrayDateTime[0];
	$byDate = date('Y-m-d',strtotime(str_replace('/', '-',$arrayDateTime[1])));
	
	$devices  = mysql_query("select * from ponto where idDevice = $idDevice" ) or die (mysql_error());
	
	$pt = mysql_fetch_array($devices);
	$jsonData .= '{"id":"'.$pt["idDevice"].'"
			      ,"nome":"'.$pt["nomePonto"].'"
				  ,"info":"'.$pt["info"].'"
				  ,"icon":"'.$pt["icone"].'"
				  ,"posicoes":[';
		
	$posicoes = mysql_query("select distinct latitude
										   , longitude
										   , velocidade
										   , datetime
			 							   , case datetime
											          when ( select max(datetime)  from package
															  where iddevice = $idDevice
																and typeData = 12
																and latitude <> '-0.000000'
																and longitude <> '-0.000000'
																and date(datetime) = '".$byDate."')
													  then 'true'
													  else ''
											  end as 'last'
										   , case datetime
											          when ( select min(datetime)  from package
															  where iddevice = $idDevice
																and typeData = 12
																and latitude <> '-0.000000'
																and longitude <> '-0.000000'
																and date(datetime) = '".$byDate."')
													  then 'true'
													  else ''
											  end as 'first'
								from package
							   where iddevice = $idDevice
								 and typeData = 12
								 and latitude <> '-0.000000'
								 and longitude <> '-0.000000'
								 and date(datetime) = '".$byDate."'")or die (mysql_error());

	while($row = mysql_fetch_array($posicoes)){

		$jsonData .= '{"latitude"   :"'.$row["latitude"].'",
				       "longitude"  :"'.$row["longitude"].'",
				       "last"       :"'.$row["last"].'",
				       "first"      :"'.$row["first"].'", 		
					   "velocidade" :"'.$row["velocidade"].'",
					   "dateTime"   :"'.date("H:i:s d-m-Y",strtotime($row["datetime"])).'"},';

	}
	$jsonData = chop($jsonData,",");
	$jsonData .=']},';
}
$jsonData = chop($jsonData,",");
$jsonData .= ']}';
echo $jsonData;
?>